package com.seven.leetcode.problems;

import com.seven.leetcode.utils.ListNode;

/**
 * 82. 删除排序链表中的重复元素 II
 * RemoveDuplicatesFromSortedArray
 * https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list/
 * 级别：Medium
 * <p>
 * 存在一个按升序排列的链表，给你这个链表的头节点 head ，请你删除链表中所有存在数字重复情况的节点，
 * 只保留原始链表中没有重复出现的数字。
 * 返回同样按升序排列的结果链表。
 * <p>
 * 示例 1:
 * 输入：head = [1,2,3,3,4,4,5]
 * 输出：[1,2,5]
 * <p>
 * 示例 2:
 * 输入：head = [1,1,1,2,3]
 * 输出：[2,3]
 *
 * @author : wenguang
 * @date : 2021/3/22 9:26
 */
public class RemoveDuplicatesFromSortedArrayByLinkedList2 {

    public static void main(String[] args) {
//        int[] nums = new int[]{1,2,3,3,4,4,5};
        int[] nums = new int[]{1, 1, 2, 3, 3, 4, 4, 5, 5};
//        int[] nums = new int[]{1,1,1};
        ListNode node = ListNode.fromArray(nums);
        System.out.println("in: \nnode->" + node);
        ListNode result = removeDuplicatesFromSortedArray(node);
        System.out.println("out: \n" + result);
    }

    public static ListNode removeDuplicatesFromSortedArray(ListNode head) {
        if (head == null) {
            return head;
        }

        head = new ListNode(head.val - 1, head);
        ListNode cur = head;
        while (cur.next != null && cur.next.next != null) {
            if (cur.next.val == cur.next.next.val) {
                int x = cur.next.val;
                while (cur.next != null && cur.next.val == x) {
                    cur.next = cur.next.next;
                }
            } else {
                cur = cur.next;
            }
        }

        return head.next;
    }
}
